package com.ht.medicaltreatment.activity

import android.media.MediaPlayer
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.githang.statusbar.StatusBarCompat
import com.gym.baselib.base.BaseActivity
import com.gym.baselib.utils.CacheUtils
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.GroupBloodAdapter
import com.ht.medicaltreatment.adapter.GroupNameAdapter
import com.ht.medicaltreatment.base.CacheKey
import com.ht.medicaltreatment.bean.CheckGroupBeanData
import com.ht.medicaltreatment.bean.CheckGroupBeanRfidSample
import com.ht.medicaltreatment.bean.CheckUidBean
import com.ht.medicaltreatment.bean.VerificationExceptionRecord
import com.ht.medicaltreatment.utils.ScanUtils
import com.ht.medicaltreatment.utils.SoundUtils
import com.ht.medicaltreatment.view.ScanErrorDialog
import com.ht.medicaltreatment.viewmodel.CheckGroupViewModel
import com.xgst.lib.utils.showToast
import kotlinx.android.synthetic.main.activity_check_group_layout.btnReplace
import kotlinx.android.synthetic.main.activity_check_group_layout.cbRX
import kotlinx.android.synthetic.main.activity_check_group_layout.cbZX
import kotlinx.android.synthetic.main.activity_check_group_layout.etRemarks
import kotlinx.android.synthetic.main.activity_check_group_layout.flLeft
import kotlinx.android.synthetic.main.activity_check_group_layout.flRight
import kotlinx.android.synthetic.main.activity_check_group_layout.imgBZ
import kotlinx.android.synthetic.main.activity_check_group_layout.imgRemarksSave
import kotlinx.android.synthetic.main.activity_check_group_layout.imgReset
import kotlinx.android.synthetic.main.activity_check_group_layout.imgTime
import kotlinx.android.synthetic.main.activity_check_group_layout.llRemarks
import kotlinx.android.synthetic.main.activity_check_group_layout.llReplace
import kotlinx.android.synthetic.main.activity_check_group_layout.recyclerView
import kotlinx.android.synthetic.main.activity_check_group_layout.recyclerViewName
import kotlinx.android.synthetic.main.activity_check_group_layout.tvCheckedTime
import kotlinx.android.synthetic.main.activity_check_group_layout.tvFenLiTime
import kotlinx.android.synthetic.main.activity_check_group_layout.tvJump
import kotlinx.android.synthetic.main.activity_check_group_layout.tvProgress
import kotlinx.android.synthetic.main.activity_check_group_layout.tvRemarkHistory
import kotlinx.android.synthetic.main.activity_check_group_layout.tvRemarks
import kotlinx.android.synthetic.main.activity_check_group_layout.tvReplaceRFID
import kotlinx.android.synthetic.main.activity_check_group_layout.viewBgGray
import kotlinx.android.synthetic.main.activity_check_group_layout.viewBgGrayReplace
import kotlinx.android.synthetic.main.include_title_layout.imgBack
import kotlinx.android.synthetic.main.view_stub_layout.imgViewStubProgress
import kotlinx.android.synthetic.main.view_stub_layout.tvViewStubProgress
import kotlinx.android.synthetic.main.view_stub_layout.viewStub

//CheckPagerFragment.createFragment("1")  之前写的
/**
 * 1、不按照顺序来，将扫描到的对应试管变绿
 * 2、扫描不对的试管，提示扫描到的uid是多少，实际需要的是那些
 * 3、不展示检验错误的
 */
class CheckGroupActivity : BaseActivity(), View.OnClickListener, OnItemChildClickListener {
    val viewModel by viewModels<CheckGroupViewModel>()
    private lateinit var adapter:GroupBloodAdapter
    private lateinit var nameAdapter:GroupNameAdapter
    //编组id集合
    private var sghyMarshallIdList = mutableListOf<Int>()
    //编组id
    private var sghyMarshallId = 0
    //当前编组位置
    private var currentPosition = 0
    //试管列表
    private var itemList:MutableList<CheckGroupBeanRfidSample> = mutableListOf()
    private var names = ""
    //核验成功的数量
    private var checkSuccessNum = 0
    //是否全部核验完成
    private var isAllChecked = false

    //0 未核验，1 已核验 2紧急跳过
    private var checkSuccess = 0
    //是否替换
    private var isReplace = false
    //被替换的旧uid
    private var oldUid = ""
    //被替换的uid的位置
    private var replacePosition = 0
    //已核验的数量
    private var haveCheckNumber = 0
    private var haveAllCheckNumber = 0

    override fun getLayoutId() = R.layout.view_stub_layout

    override fun init() {
        viewStub.setOnInflateListener { viewStub, view ->
            tvViewStubProgress.visibility = View.GONE
            imgViewStubProgress.visibility = View.GONE

            setTitle("核验分装")
            StatusBarCompat.setStatusBarColor(this,getColor(R.color.white))

            ScanUtils.init()

            initRecycerView()
            sghyMarshallId = intent.getIntExtra("id",0)
            LogUtils.i("sghyMarshallId: $sghyMarshallId")
            currentPosition = intent.getIntExtra("poistion",0)
            initData()
            initClick()
        }

        viewStub.postDelayed({
            viewStub.layoutResource = R.layout.activity_check_group_layout
            viewStub.inflate()
        },300)
    }

    private fun initClick() {
        //脂血 0是  1不是
        cbZX.setOnClickListener(this)
        cbRX.setOnClickListener(this)
        imgReset.setOnClickListener(this)
        flRight.setOnClickListener(this)
        flLeft.setOnClickListener(this)
        imgTime.setOnClickListener(this)

        imgBZ.setOnClickListener(this)
        tvRemarks.setOnClickListener(this)
        tvJump.setOnClickListener(this)
        imgRemarksSave.setOnClickListener(this)
        imgBack.setOnClickListener(this)
        btnReplace.setOnClickListener(this)
        viewBgGray.setOnClickListener(this)
    }

    private fun initRecycerView() {
        //试管列表
        adapter = GroupBloodAdapter()
        recyclerView.layoutManager = LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
        recyclerView.adapter = adapter
        adapter.setOnItemChildClickListener(this)

        //试管的标题列表
        recyclerViewName.layoutManager = LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
        nameAdapter = GroupNameAdapter()
        recyclerViewName.adapter = nameAdapter
    }

    //获取数据
    private fun initData() {
        showProgress()

        reset()

        viewModel.requestData("$sghyMarshallId", {
            dismissProgress()
            checkSuccess = it.sghyMarshall.checkSuccess
            itemList = it.sghyMarshall.rfidSampleList
            haveCheckNumber = it.haveCheckNumber
            haveAllCheckNumber = it.sghyMarshallIdList.size
            tvProgress.text = "核验进度$haveCheckNumber/$haveAllCheckNumber"
            sghyMarshallIdList = it.sghyMarshallIdList
            itemList.forEach {
                names += "${it.name}、"
            }
            if(checkSuccess == 0){
                //未核验
                startScan()
            }else if(checkSuccess == 1){
                //已核验
                isAllChecked = true
                itemList.forEach {
                    it.checkType = 1
                }
            }

            initView(it)
            adapter.setNewInstance(itemList)
            nameAdapter.setNewInstance(itemList)
        }, {
            dismissProgress()
            showToast(it)
        })
    }
    var historyRemark = ""
    //已核验后，回显数据
    private fun initView(it: CheckGroupBeanData) {
        if(it.sghyMarshall.checkTime != null){
            imgReset.visibility = View.INVISIBLE
            tvCheckedTime.setTextColor(getColor(R.color.green))
            tvCheckedTime.text = "核验时间\n${it.sghyMarshall.checkTime}"
        }
        if(it.sghyMarshall.centrifugalTime != null){
            imgTime.visibility = View.INVISIBLE
            tvFenLiTime.setTextColor(getColor(R.color.green))
            tvFenLiTime.text = "分装时间\n${it.sghyMarshall.centrifugalTime}"
        }
        if(!TextUtils.isEmpty(it.sghyMarshall.globalRemark)){
            historyRemark = it.sghyMarshall.globalRemark
        }
        tvRemarkHistory.setText("历史备注：${it.sghyMarshall.globalRemark}")
        if(it.sghyMarshall.isEsterBlood == 1){
            cbZX.isChecked = true
        }
        if(it.sghyMarshall.isHemolysis == 1){
            cbRX.isChecked = true
        }
        if(checkSuccess == 2){
           tvJump.setBackgroundResource(R.drawable.icon_jump_stop)
        }else{
            tvJump.setBackgroundResource(R.drawable.bg_jump)
        }

    }

    //切换分组钱 复位数据
    private fun reset() {
        adapter.setNewInstance(null)
        nameAdapter.setNewInstance(null)
        tvProgress.text = "核验进度0/0"
        sghyMarshallIdList.clear()
        etRemarks.setText("")
        cbZX.isChecked = false
        cbRX.isChecked = false
        names = ""
        checkSuccessNum = 0
        imgReset.visibility = View.VISIBLE
        tvCheckedTime.text = "重新核验样本\nRestart Group Checking"
        tvCheckedTime.setTextColor(getColor(R.color.white))

        imgTime.visibility = View.VISIBLE
        tvFenLiTime.text = "记录分装时间\nRecord Packing Time"
        tvFenLiTime.setTextColor(getColor(R.color.white))

        cbRX.isEnabled = true
        cbZX.isEnabled = true
        etRemarks.isEnabled = true

        isAllChecked = false
    }

    //开始核验
    private fun startScan() {
        ScanUtils.open { uid ->
            if(isReplace){
                //替换试管
                SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
                tvReplaceRFID.text = uid
                return@open
            }
            var checkSuccess = false
            itemList.forEach {
                if(it.rfidCode == uid){
                    SoundUtils.playSound(SoundUtils.CHECK_SUCCESS)
                    var position = adapter.getItemPosition(it)
                    it.checkType = 1
                    adapter.notifyItemChanged(position)
                    nameAdapter.notifyItemChanged(position)
                    checkSuccess = true
                    checkSuccessNum++
                    return@forEach
                }
            }
            if(!checkSuccess){
                ScanUtils.resetItem(uid)
                //核验错误，提示应该需要的试管名字和扫描的错误试管名字
                SoundUtils.playSound(SoundUtils.CHECK_ERROR)
                showProgress()
                viewModel.searchName(arrayListOf(uid),{
                    dismissProgress()
                    ScanErrorDialog(this).show(names,it[0])
                },{
                    dismissProgress()
                    showToast(it)
                })
            }
            if(checkSuccessNum == itemList.size){
                submitData()
            }
        }
    }

    //全部核验成功  提交核验数据
    private fun submitData() {
        ScanUtils.close()
        showProgress()
        val uidList = mutableListOf<String>()
        val orderId = CacheUtils.getStringCache(CacheKey.ORDER_ID)
        //因为有替换的uid，所以需要从adapter中获取最新的uid
        adapter.data.forEach {
            uidList += it.rfidCode
        }
        val bean = VerificationExceptionRecord("301医院","SGHY")
        val json = CheckUidBean(uidList,orderId,sghyMarshallId,bean)
        viewModel.submitData(json,{
            dismissProgress()
            showToast("全部核验正确")
            isAllChecked = true
            tvProgress.text = "核验进度${haveCheckNumber+1}/$haveAllCheckNumber"
            setCheckTime()
        },{
            dismissProgress()
            showToast(it)
        })
    }

    //获取服务器的核验和分装时间
    private fun setCheckTime() {
        showProgress()
        viewModel.getTime("$sghyMarshallId",{checkTime,centrifugalTime ->
            dismissProgress()
            if(checkTime?.isNotEmpty() == true){
                imgReset.visibility = View.INVISIBLE
                tvCheckedTime.setTextColor(getColor(R.color.green))
                tvCheckedTime.text = "核验时间\n$checkTime"
            }

            if(centrifugalTime?.isNotEmpty() == true){
                imgTime.visibility = View.INVISIBLE
                tvFenLiTime.setTextColor(getColor(R.color.green))
                tvFenLiTime.text = "分装时间\n$centrifugalTime"
            }
        },{
            dismissProgress()
            showToast(it)
        })
    }

    private var remark = ""
    override fun onClick(v: View?) {
        when(v){
            //备注
            imgBZ,tvRemarks -> {
                llRemarks.visibility = View.VISIBLE
                viewBgGray.visibility = View.VISIBLE
                remark = etRemarks.text.toString()
            }
            //提交备注
            imgRemarksSave -> {
                llRemarks.visibility = View.GONE
                viewBgGray.visibility = View.GONE
                if(etRemarks.text.toString().isEmpty()||etRemarks.text.toString() == remark){
                    return
                }
                showProgress()
                viewModel.checkGroupRemarks(etRemarks.text.toString(),"$sghyMarshallId",{
                    dismissProgress()
                    showToast("添加备注成功")
                    if(historyRemark == ""){
                        tvRemarkHistory.setText("历史备注：${etRemarks.text}")
                    }else{
                        tvRemarkHistory.setText("历史备注：${historyRemark},${etRemarks.text}")
                    }
                    etRemarks.setText("")
                },{
                    dismissProgress()
                    showToast(it)
                })
            }
            //紧急跳过
            tvJump -> {
                if(isAllChecked){
                    showToast("已完成核验，无法跳过")
                    return
                }
                if(checkSuccess == 2){
                    showToast("不能重复跳过")
                    return
                }
                showProgress()
                val orderId = CacheUtils.getIntCache(CacheKey.ORDER_ID)
                viewModel.jump("$orderId","$sghyMarshallId",{
                    if(sghyMarshallIdList.size - 1 > currentPosition){
                        sghyMarshallId = sghyMarshallIdList[currentPosition++]
                        //获取下一组信息
                        initData()
                    }else{
                        dismissProgress()
                        showToast("已经是最后一组了")
                    }
                },{
                    dismissProgress()
                    showToast(it)
                })
            }
            //重新核验
            imgReset -> {
                if(isAllChecked){
                    showToast("已全部核验完成")
                    return
                }
                if(checkSuccess == 2){
                    showToast("已跳过，不能重新核验")
                    return
                }
                ScanUtils.reset()
                ScanUtils.close()
                //reset()
                initData()
            }
            //下一组
            flRight -> {
                if(sghyMarshallIdList.size - 1 > currentPosition){
                    currentPosition = currentPosition+1
                    sghyMarshallId = sghyMarshallIdList[currentPosition]
                    initData()
                }else{
                    showToast("当前是最后一组")
                }
            }
            //上一组
            flLeft -> {
                if(currentPosition > 0){
                    currentPosition = currentPosition-1
                    sghyMarshallId = sghyMarshallIdList[currentPosition]
                    initData()
                }else{
                    showToast("当前是第一组")
                }
            }
            //记录分装时间
            imgTime -> {
                if(!isAllChecked){
                    showToast("还没有完成核验")
                    return
                }
                showProgress()
                viewModel.updateTime(sghyMarshallId,{
                    dismissProgress()
                    MediaPlayer.create(this,R.raw.recording_subpackage_time).start()
                    setCheckTime()
                },{
                    dismissProgress()
                    showToast(it)
                })
            }
            //替换
            btnReplace -> {
                if(tvReplaceRFID.text.toString() != "RFID编号"){
                    showProgress()
                    val newUid = tvReplaceRFID.text.toString()
                    viewModel.replace(oldUid,newUid,{
                        dismissProgress()
                        isReplace = false
                        llReplace.visibility = View.GONE
                        viewBgGrayReplace.visibility = View.GONE
                        showToast("替换成功")
                        checkSuccessNum++
                        //更新试管
                        adapter.getItem(replacePosition).rfidCode = newUid
                        adapter.getItem(replacePosition).checkType = 1
                        adapter.notifyItemChanged(replacePosition)
                        //更新试管上方名字
                        nameAdapter.getItem(replacePosition).rfidCode = newUid
                        nameAdapter.getItem(replacePosition).checkType = 1
                        nameAdapter.notifyItemChanged(replacePosition)
                        adapter.data.forEach {
                            LogUtils.i("${adapter.getItemPosition(it)}  ${it.name} : ${it.rfidCode}")
                        }
                        if(checkSuccessNum == itemList.size){
                            submitData()
                        }
                    },{
                        dismissProgress()
                        showToast(it)
                    })
                }
            }
            //溶血
            cbRX -> {
                showProgress()
                viewModel.rongXue(if (cbRX.isChecked) "1" else "0","$sghyMarshallId",{
                    dismissProgress()
                },{
                    dismissProgress()
                    showToast(it)
                })
            }
            //脂血
            cbZX -> {
                showProgress()
                viewModel.ziXue(if (cbZX.isChecked) "1" else "0","$sghyMarshallId",{
                    dismissProgress()
                },{
                    dismissProgress()
                    showToast(it)
                })
            }
            imgBack -> finish()
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if(keyCode == KeyEvent.KEYCODE_BACK
            && llRemarks.visibility == View.VISIBLE
            || llReplace.visibility == View.VISIBLE){
            llRemarks.visibility = View.GONE
            viewBgGray.visibility = View.GONE
            llReplace.visibility = View.GONE
            viewBgGrayReplace.visibility = View.GONE
            isReplace = false
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        super.onDestroy()
        ScanUtils.onDestroy()
    }

    /**
     * 试管替换
     */
    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val item = adapter.getItem(position) as CheckGroupBeanRfidSample
        tvReplaceRFID.text = "RFID编号"
        viewBgGrayReplace.visibility = View.VISIBLE
        llReplace.visibility = View.VISIBLE
        isReplace = true
        oldUid = item.rfidCode
        replacePosition = position
    }
}
